import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { Category, PaginationResponse, QueryParams } from '@/types/admin'
import { api, API_ENDPOINTS } from '@/utils/api'
import { ElMessage } from 'element-plus'

export const useCategoryStore = defineStore('category', () => {
  // 状态
  const categories = ref<Category[]>([])
  const categoryTree = ref<Category[]>([])
  const currentCategory = ref<Category | null>(null)
  const pagination = ref({
    page: 1,
    limit: 20,
    total: 0,
    pages: 0
  })
  const isLoading = ref(false)
  const allCategories = ref<Category[]>([])

  // 获取分类列表
  const fetchCategories = async (params: QueryParams = {}) => {
    try {
      isLoading.value = true
      
      // 构建查询参数
      const queryParams: any = {
        page: params.page || 1,
        limit: params.limit || 20,
        include: 'parent' // 添加 parent 关系
      }
      
      // 添加其他查询参数
      if (params.search) queryParams.search = params.search
      if (params.isActive !== undefined) queryParams.isActive = params.isActive
      if (params.parentId !== undefined) queryParams.parentId = params.parentId
      
      console.log('发送查询参数:', queryParams)
      
      const response = await api.get<PaginationResponse<Category>>(
        API_ENDPOINTS.CATEGORIES,
        queryParams
      )
      
      console.log('后端响应:', response.data)
      
      // 处理后端返回的分页数据结构
      if (response.data?.data && response.data?.pagination) {
        // 标准分页格式: {data: [...], pagination: {...}}
        categories.value = response.data.data
        pagination.value = {
          page: response.data.pagination.page,
          limit: response.data.pagination.limit,
          total: response.data.pagination.total,
          pages: response.data.pagination.pages
        }
        console.log('使用标准分页格式，分页信息:', pagination.value)
      } else if (Array.isArray(response.data)) {
        // 兼容直接返回数组格式: [...] (后端应该修复为标准格式)
        categories.value = response.data
        
        // 智能分页处理：根据返回的数据量判断分页情况
        const returnedCount = response.data.length
        const requestedLimit = queryParams.limit
        const currentPage = queryParams.page
        
        // 如果返回的数据等于请求的limit，可能还有更多数据
        // 如果返回的数据少于limit，说明这是最后一页
        const hasMoreData = returnedCount === requestedLimit
        
        let estimatedTotal: number
        if (currentPage === 1 && !hasMoreData) {
          // 第一页就没有满数据，总数就是当前数据量
          estimatedTotal = returnedCount
        } else if (!hasMoreData) {
          // 不是第一页且数据未满，计算精确总数
          estimatedTotal = (currentPage - 1) * requestedLimit + returnedCount
        } else {
          // 数据已满，估算至少还有更多数据
          estimatedTotal = currentPage * requestedLimit + 1
        }
        
        pagination.value = {
          page: currentPage,
          limit: requestedLimit,
          total: estimatedTotal,
          pages: Math.ceil(estimatedTotal / requestedLimit)
        }
        
        console.log(`兼容模式分页: 第${currentPage}页，返回${returnedCount}/${requestedLimit}条，估算总数${estimatedTotal}`)
        console.log('计算的分页信息:', pagination.value)
      } else {
        console.error('未知的响应格式:', response.data)
        categories.value = []
        pagination.value = {
          page: 1,
          limit: 20,
          total: 0,
          pages: 0
        }
      }
      
      console.log('最终分类数据条数:', categories.value.length)
      console.log('最终分页信息:', pagination.value)
      
    } catch (error) {
      console.error('获取分类列表失败:', error)
      ElMessage.error('获取分类列表失败')
      categories.value = []
      pagination.value = {
        page: 1,
        limit: 20,
        total: 0,
        pages: 0
      }
    } finally {
      isLoading.value = false
    }
  }

  // 获取分类树
  const fetchCategoryTree = async () => {
    try {
      const response = await api.get<Category[]>(API_ENDPOINTS.CATEGORIES_TREE)
      if (response.data) {
        categoryTree.value = response.data
      }
    } catch (error) {
      console.error('获取分类树失败:', error)
      ElMessage.error('获取分类树失败')
    }
  }

  // 获取分类详情
  const fetchCategoryById = async (id: number) => {
    try {
      isLoading.value = true
      const response = await api.get<Category>(`${API_ENDPOINTS.CATEGORIES}/${id}`)
      if (response.data) {
        currentCategory.value = response.data
      }
      return response.data
    } catch (error) {
      console.error('获取分类详情失败:', error)
      ElMessage.error('获取分类详情失败')
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 根据slug获取分类
  const fetchCategoryBySlug = async (slug: string) => {
    try {
      isLoading.value = true
      const response = await api.get<Category>(`/categories/slug/${slug}`)
      if (response.data) {
        currentCategory.value = response.data
      }
      return response.data
    } catch (error) {
      console.error('获取分类详情失败:', error)
      ElMessage.error('获取分类详情失败')
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 创建分类
  const createCategory = async (categoryData: Partial<Category>) => {
    try {
      const response = await api.post<Category>(API_ENDPOINTS.CATEGORIES, categoryData)
      if (response.data) {
        categories.value.unshift(response.data)
        ElMessage.success('分类创建成功')
        return response.data
      }
    } catch (error) {
      console.error('创建分类失败:', error)
      ElMessage.error('创建分类失败')
      throw error
    }
  }

  // 更新分类
  const updateCategory = async (id: number, categoryData: Partial<Category>) => {
    try {
      // 确保 parentId 为 null 时也能正确处理
      const dataToUpdate = {
        ...categoryData,
        parentId: categoryData.parentId === null ? null : categoryData.parentId
      }
      
      const response = await api.put<Category>(`${API_ENDPOINTS.CATEGORIES}/${id}`, dataToUpdate)
      if (response.data) {
        const index = categories.value.findIndex(c => c.id === id)
        if (index !== -1) {
          categories.value[index] = response.data
        }
        if (currentCategory.value?.id === id) {
          currentCategory.value = response.data
        }
        ElMessage.success('分类更新成功')
        return response.data
      }
    } catch (error) {
      console.error('更新分类失败:', error)
      ElMessage.error('更新分类失败')
      throw error
    }
  }

  // 删除分类
  const deleteCategory = async (id: number) => {
    try {
      await api.delete(`${API_ENDPOINTS.CATEGORIES}/${id}`)
      categories.value = categories.value.filter(c => c.id !== id)
      if (currentCategory.value?.id === id) {
        currentCategory.value = null
      }
      ElMessage.success('分类删除成功')
    } catch (error) {
      console.error('删除分类失败:', error)
      ElMessage.error('删除分类失败')
      throw error
    }
  }

  // 批量删除分类
  const deleteCategoriesBatch = async (ids: number[]) => {
    try {
      await Promise.all(ids.map(id => api.delete(`${API_ENDPOINTS.CATEGORIES}/${id}`)))
      categories.value = categories.value.filter(c => !ids.includes(c.id))
      ElMessage.success(`成功删除 ${ids.length} 个分类`)
    } catch (error) {
      console.error('批量删除分类失败:', error)
      ElMessage.error('批量删除分类失败')
      throw error
    }
  }

  // 切换分类状态
  const toggleCategoryStatus = async (id: number, isActive: boolean) => {
    try {
      const response = await api.put<Category>(`${API_ENDPOINTS.CATEGORIES}/${id}`, { isActive })
      if (response.data) {
        const index = categories.value.findIndex(c => c.id === id)
        if (index !== -1) {
          categories.value[index] = response.data
        }
        ElMessage.success(`分类已${isActive ? '启用' : '禁用'}`)
        return response.data
      }
    } catch (error) {
      console.error('切换分类状态失败:', error)
      ElMessage.error('切换分类状态失败')
      throw error
    }
  }

  // 清空当前分类
  const clearCurrentCategory = () => {
    currentCategory.value = null
  }

  // 重置状态
  const reset = () => {
    categories.value = []
    categoryTree.value = []
    currentCategory.value = null
    pagination.value = {
      page: 1,
      limit: 20,
      total: 0,
      pages: 0
    }
    isLoading.value = false
  }

  // 获取分类树（用于选择父分类）
  const getCategoryTree = () => {
    return categories.value.map(category => ({
      ...category,
      children: categories.value.filter(c => c.parentId === category.id)
    })).filter(category => !category.parentId) // 只返回顶级分类
  }

  // 获取所有分类（用于选择器）
  const fetchAllCategories = async () => {
    try {
      const response = await api.get<{ data: Category[] }>(API_ENDPOINTS.CATEGORIES, {
        limit: 1000,
        page: 1
      })
      
      if (Array.isArray(response.data)) {
        allCategories.value = response.data
      } else if (response.data && Array.isArray(response.data.data)) {
        allCategories.value = response.data.data
      }
      
      return allCategories.value
    } catch (error) {
      console.error('获取所有分类失败:', error)
      return []
    }
  }

  return {
    // 状态
    categories,
    categoryTree,
    currentCategory,
    pagination,
    isLoading,
    allCategories,

    // 方法
    fetchCategories,
    fetchCategoryTree,
    fetchCategoryById,
    fetchCategoryBySlug,
    createCategory,
    updateCategory,
    deleteCategory,
    deleteCategoriesBatch,
    toggleCategoryStatus,
    clearCurrentCategory,
    reset,
    getCategoryTree,
    fetchAllCategories
  }
}) 